package com.wandian.weather.mvvm.moredayweather;

import android.os.Bundle;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.adapter.BasePagerAdapter;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.widget.MyLinearLayoutManager;
import com.wandian.weather.R;
import com.wandian.weather.adapter.CoolingAdapter;
import com.wandian.weather.adapter.WarningAdapter;
import com.wandian.weather.bean.AqiBean;
import com.wandian.weather.bean.TianqiWeather30Bean;
import com.wandian.weather.bean.WeatherInformationBean;
import com.wandian.weather.databinding.WeatherActivityMoreDayWatherBinding;
import com.wandian.weather.mvvm.moredayweather.pagefragment.ChildPageFragment;
import com.wandian.weather.tools.WeatherUtil;
import com.wandian.weather.view.CustomCurveChart;
import com.wandian.weather.view.YtPieView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.mylib.libcore.config.AppSPKeyConfig.CITY_NAME;

/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 更多天气
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_WEATHER_MORE_DAY_WEATHER)
public class MoreDayWeatherActivity extends BaseMVVMActivity<MoreDayWeatherViewModel> implements ChildPageFragment.CalendarItemClink {
    private WeatherActivityMoreDayWatherBinding dataBinding;
    private WeatherInformationBean weatherInformationBean;
    private TianqiWeather30Bean weather30Bean;
    private BasePagerAdapter myAdapter;
    private List<String> titleList=new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private String mCTime;
    private String cityID;
    private List<TianqiWeather30Bean.WeatherDaysBean> weatherDaysBeans;
    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.weather_activity_more_day_wather);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);
        dataBinding.bindSysToolBar.toolBarTvTitle.setText("重庆");
        cityID = getIntent().getStringExtra("cityID");
        String weatherJson = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("WeatherInformationBean");
        if(!UIUtils.isEmpty(weatherJson)){
            weatherInformationBean = (WeatherInformationBean) JsonUtil.parseJsonToBean(weatherJson,WeatherInformationBean.class);
        }
        initClink();
        initViewData();
        if(!UIUtils.isEmpty(cityID))mViewModel.getWeatherData(cityID);
    }

    private void initViewData(){
        String city_name = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(CITY_NAME);
        if(!UIUtils.isEmpty(city_name)){
            dataBinding.bindSysToolBar.toolBarTvTitle.setText(city_name);
        }else {
            dataBinding.bindSysToolBar.toolBarTvTitle.setText("所在城市");
        }

        initCalenerView();
        mViewModel.tianqiWeather30Bean.observe(this,bean->{
            if(!UIUtils.isEmpty(bean)){
                this.weather30Bean =bean;
                initTempView();
            }
        });
    }

    //气温折线图
    private void initTempView(){
        try {
            String htemp_date =weather30Bean.getHtemp().getCdate();
            String htemp_num = weather30Bean.getHtemp().getTemp();
            dataBinding.tvNew30daysHtemp.setText(htemp_date + "温度最高");
            dataBinding.tvNew30daysHtempNum.setText(htemp_num + "°");
            String ltemp_date = weather30Bean.getLtemp().getCdate();
            String ltemp_num = weather30Bean.getLtemp().getTemp();
            dataBinding.tvNew30daysLtemp.setText(ltemp_date + "温度最低");
            dataBinding.tvNew30daysLtempNum.setText(ltemp_num + "°");

            weatherDaysBeans = weather30Bean.getWeather_days();
            if(!UIUtils.isEmpty(weatherDaysBeans) && weatherDaysBeans.size()>0){
                mCTime = weatherDaysBeans.get(0).getNl().getDate();
                initWeather(weatherDaysBeans.get(0));
                initChart(weather30Bean);
            }

            initPieChart(weather30Bean);
            warningOrcooling(weather30Bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //降温
    private void warningOrcooling(TianqiWeather30Bean weather30Bean){
        TianqiWeather30Bean.LowtempBean lowtempBean = weather30Bean.getLowtemp();
        int lowNum = 0;
        if(!UIUtils.isEmpty(lowtempBean) && !UIUtils.isEmpty(lowtempBean.getData()))lowNum =lowtempBean.getData().size();
        if(lowNum == 0){
            dataBinding.llCoolingTimes.setVisibility(View.GONE);
        }else {
            dataBinding.llCoolingTimes.setVisibility(View.VISIBLE);
            dataBinding.rtCoolingTimes.setText("往后可能"+lowNum + "次降温");
            MyLinearLayoutManager coolingLayoutManager = new MyLinearLayoutManager(this);
            coolingLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            dataBinding.rvNew30daysCooling.setLayoutManager(coolingLayoutManager);
            dataBinding.rvNew30daysCooling.setAdapter(new CoolingAdapter(R.layout.weather_item_warning_cooling, weather30Bean.getLowtemp().getData()));
        }

        TianqiWeather30Bean.UptempBean uptempBean = weather30Bean.getUptemp();
        int upNum = 0;
        if(!UIUtils.isEmpty(uptempBean) && !UIUtils.isEmpty(uptempBean.getData()))upNum=uptempBean.getData().size();
        if(upNum == 0){
            dataBinding.llWarmingTimes.setVisibility(View.GONE);
        }else {
            dataBinding.llWarmingTimes.setVisibility(View.VISIBLE);
            dataBinding.rtWarmingTimes.setText("往后可能"+upNum + "次升温");
            MyLinearLayoutManager warningLayoutManager = new MyLinearLayoutManager(this);
            warningLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            dataBinding.rvNew30daysWarming.setLayoutManager(warningLayoutManager);
            dataBinding.rvNew30daysWarming.setAdapter(new WarningAdapter(R.layout.weather_item_warning_cooling, weather30Bean.getUptemp().getData()));
        }
    }

    //折线图
    private void initChart(TianqiWeather30Bean weather30Bean){
        float ltemp = Float.parseFloat(weather30Bean.getLtemp().getTemp());
        float htemp = Float.parseFloat(weather30Bean.getHtemp().getTemp());

        float min = ltemp - 5;
        float max = htemp + 5;


        String[] xLabel = new String[weatherDaysBeans.size()];
        String[] yLabel = {ltemp+"°", htemp+"°"};
        List<Float> data = new ArrayList<>();

        for (int i=0; i<weatherDaysBeans.size(); i++){
            TianqiWeather30Bean.WeatherDaysBean pre = weatherDaysBeans.get(i);
            xLabel[i] = pre.getCdate();
            float yl = Float.parseFloat(pre.getStemp());
            data.add(yl);
        }

        TianqiWeather30Bean.LowtempBean lowtempBean = weather30Bean.getLowtemp();
        double tempLow = 0;
        TianqiWeather30Bean.LowtempBean.DataBean.CdateBean lowCdate = null;
        if(lowtempBean!=null && lowtempBean.getData()!=null ) {
            for (int i = 0; i < lowtempBean.getData().size(); i++) {
                TianqiWeather30Bean.LowtempBean.DataBean dataBean = lowtempBean.getData().get(i);
                if (tempLow < dataBean.getTemp()) {
                    tempLow = dataBean.getTemp();
                    lowCdate = dataBean.getCdate();
                }
            }
        }

        TianqiWeather30Bean.UptempBean uptempBean = weather30Bean.getUptemp();
        double tempUp = 0;
        TianqiWeather30Bean.UptempBean.DataBeanX.CdateBeanX upCdate = null;
        if(uptempBean!=null && uptempBean.getData()!=null) {
            for (int i = 0; i < uptempBean.getData().size(); i++) {
                TianqiWeather30Bean.UptempBean.DataBeanX dataBean = uptempBean.getData().get(i);
                if (tempUp < dataBean.getTemp()) {
                    tempUp = dataBean.getTemp();
                    upCdate = dataBean.getCdate();
                }
            }
        }

        dataBinding.chartTemperature.addView(new CustomCurveChart(this, xLabel, yLabel, data, max, min, upCdate, lowCdate));
    }

    //圆形图
    private void initPieChart(TianqiWeather30Bean weather30Bean){
        List<YtPieView.Data> datas = new ArrayList<>();
        int[] colors ={0xff6e58ff, 0xff00b3fd, 0xff0fa2ef, 0xff6bc5f4, 0xffb3e5ff};
        List<TianqiWeather30Bean.WeatherFbBean> weatherFbBeans = weather30Bean.getWeather_fb();
        for (TianqiWeather30Bean.WeatherFbBean wb : weatherFbBeans){
            String weather = wb.getName()+" "+wb.getNum()+"天";
            int resId = WeatherUtil.getWeatherSmallImage(String.valueOf(wb.getImg_num()), false);
            int color =0;
            switch (wb.getName()){
                case "晴":
                    color = colors[0];
                    break;
                case "雨":
                    color = colors[3];
                    break;
                case "阴":
                    color = colors[2];
                    break;
                case "多云":
                    color = colors[1];
                    break;
                case "雪":
                    color = colors[4];
                    break;
                default:
                    color = colors[0];
                    break;

            }
            datas.add(new YtPieView.Data(weather, wb.getNum(), color, resId));
        }

        dataBinding.pieChart.setData(datas);
    }


    private void initWeather(TianqiWeather30Bean.WeatherDaysBean wb){
        int resId = WeatherUtil.getWeatherStateImage(String.valueOf(wb.getImg_num()), false);
        dataBinding.imgTem.setImageResource(resId);
        dataBinding.tvTemperatureTips.setText(wb.getWeather());
        dataBinding.tvData.setText(wb.getCdate()+"");
        dataBinding.tvTemperature.setText(wb.getLtemp()+"~"+wb.getHtemp());
        try {
            AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(wb.getAqi()));
            if(!UIUtils.isEmpty(aqiBean))  dataBinding.tvWeatherKqzl.setText("空气质量:"+aqiBean.getAqiName());
        }catch (Exception e){

        }
        dataBinding.tvWeatherTigan.setText("体感:"+wb.getStemp());
    }


    //日期天气
    private void initCalenerView() {
        try {
            Calendar calendarMin = Calendar.getInstance();
            int year = calendarMin.get(Calendar.YEAR);
            int month = calendarMin.get(Calendar.MONTH)+1;
            dataBinding.tvCalendarDate.setText(String.format("%s年 %s月", year, month));

            titleList.add("1");
            titleList.add("2");
            for(int i=0;i<titleList.size();i++){
                fragments.add(ChildPageFragment.newInstance(titleList.get(i).trim(),cityID));
            }
            myAdapter = new BasePagerAdapter(getSupportFragmentManager(), fragments,titleList);
            if(UIUtils.isEmpty(dataBinding.calendarViewpager.getAdapter())){
                dataBinding.calendarViewpager.setAdapter(myAdapter);
                dataBinding.calendarViewpager.setOffscreenPageLimit(titleList.size());
            }
            if(!UIUtils.isEmpty(myAdapter)){
                myAdapter.notifyDataSetChanged();
            }
            dataBinding.calendarViewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    if(position == 0){
                        //日期
                        dataBinding.imgCalendarLeft.setAlpha(0.4f);
                        dataBinding.imgCalendarRight.setAlpha(1f);
                        dataBinding.imgCalendarLeft.setClickable(false);
                        dataBinding.imgCalendarRight.setClickable(true);
                        Calendar calendarMin = Calendar.getInstance();
                        int year = calendarMin.get(Calendar.YEAR);
                        int month = calendarMin.get(Calendar.MONTH)+1;
                        dataBinding.tvCalendarDate.setText(String.format("%s年 %s月", year, month));
                    }else {
                        dataBinding.imgCalendarLeft.setAlpha(1f);
                        dataBinding.imgCalendarRight.setAlpha(0.4f);
                        dataBinding.imgCalendarLeft.setClickable(true);
                        dataBinding.imgCalendarRight.setClickable(false);
                        Calendar calendarMin2 = Calendar.getInstance();
                        calendarMin2.add(Calendar.MONTH, 1);
                        int year2 = calendarMin2.get(Calendar.YEAR);
                        int month2 = calendarMin2.get(Calendar.MONTH)+1;
                        dataBinding.tvCalendarDate.setText(String.format("%s年 %s月", year2, month2));
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void initClink(){
        dataBinding.bindSysToolBar.toolBarIvBack.setOnClickListener(v -> {
            finish();
        });

        dataBinding.imgCalendarLeft.setOnClickListener(v -> {
            //日期
            dataBinding.imgCalendarLeft.setAlpha(0.4f);
            dataBinding.imgCalendarRight.setAlpha(1f);
            dataBinding.imgCalendarLeft.setClickable(false);
            dataBinding.imgCalendarRight.setClickable(true);
            Calendar calendarMin = Calendar.getInstance();
            int year = calendarMin.get(Calendar.YEAR);
            int month = calendarMin.get(Calendar.MONTH)+1;
            dataBinding.tvCalendarDate.setText(String.format("%s年 %s月", year, month));

            dataBinding.calendarViewpager.setCurrentItem(0);
        });

        dataBinding.imgCalendarRight.setOnClickListener(v -> {
            dataBinding.imgCalendarLeft.setAlpha(1f);
            dataBinding.imgCalendarRight.setAlpha(0.4f);
            dataBinding.imgCalendarLeft.setClickable(true);
            dataBinding.imgCalendarRight.setClickable(false);
            Calendar calendarMin2 = Calendar.getInstance();
            calendarMin2.add(Calendar.MONTH, 1);
            int year2 = calendarMin2.get(Calendar.YEAR);
            int month2 = calendarMin2.get(Calendar.MONTH)+1;
            dataBinding.tvCalendarDate.setText(String.format("%s年 %s月", year2, month2));
            dataBinding.calendarViewpager.setCurrentItem(1);
        });
    }


    @Override
    public void itemOneDayData(String dayNumber) {
        for(int i=0;i<weather30Bean.getWeather_days().size();i++){
            if(!UIUtils.isEmpty(weather30Bean.getWeather_days().get(i)) && !UIUtils.isEmpty(weather30Bean.getWeather_days().get(i).getCdate())){
                if(weather30Bean.getWeather_days().get(i).getCdate().equals(dayNumber)){
                    if(!UIUtils.isEmpty(weatherDaysBeans) && weatherDaysBeans.size()>0){
                        mCTime = weatherDaysBeans.get(i).getNl().getDate();
                        initWeather(weatherDaysBeans.get(i));
                    }
                    return;
                }
            }
        }

    }
}
